package com.tanhua.dubbo.api.impl.mongo;

import com.tanhua.domain.mongo.FollowUser;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.mongo.VideoApi;
import com.tanhua.dubbo.utils.IdService;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service(timeout = 500000)
public class VideoApiImpl implements VideoApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdService idService;

    @Override
    public PageResult queryVideoList(Integer page, Integer pagesize,Long...userId) {
        //db.video.find().sort({created:-1}).limit(10).skip(0)
        //1. 构造条件
        Query query = new Query();
        // 判断条件
        if (userId != null && userId.length > 0) {
            query.addCriteria(Criteria.where("userId").is(userId[0]));
        }
        query.with(Sort.by(Sort.Order.desc("created")));
        query.limit(pagesize).skip((page-1)*pagesize);
        //2. 分页查询
        List<Video> videoList = mongoTemplate.find(query, Video.class);
        //3. 统计
        long count = mongoTemplate.count(query, Video.class);
        return new PageResult(page,pagesize, (int) count,videoList);
    }

    @Override
    public void save(Video video) {
        //设置id，用于推荐系统推荐计算
        video.setVid(idService.getNextId("video"));
        mongoTemplate.insert(video);
    }

    @Override
    public void userFocus(FollowUser followUser) {
        mongoTemplate.insert(followUser);
    }

    @Override
    public void userUnFocus(Long userId, Long followUserId) {
        // 删除条件
        Query query = new Query(
                Criteria.where("userId").is(userId)
                .and("followUserId").is(followUserId)
        );
        // 根据条件删除
        mongoTemplate.remove(query,FollowUser.class);
    }

    @Override
    public Video findById(String videoId) {
        return mongoTemplate.findById(new ObjectId(videoId),Video.class);
    }

    @Override
    public List<Video> findByVids(List<Long> pidList) {
        Query query = Query.query(Criteria.where("vid").in(pidList));
        return mongoTemplate.find(query,Video.class);
    }
}
